<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
              v-for="item in nursing_project_status"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['nursing:plan:add']"
        >新增</el-button>
      </el-col>
    </el-row>
    <br>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="200"/>
      <el-table-column label="名称" align="center" prop="planName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="large">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:plan:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="handleGet(scope.row)" v-hasPermi="['nursing:plan:get']">查看</el-button>
          <el-button link type="primary" :icon="scope.row.status === 1 ? 'Lock' : 'Unlock'"
                     @click="handleEnable(scope.row)" v-hasPermi="['nursing:plan:edit']">
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改护理计划对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="护理计划名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number v-model="form.orderNo" :min="1"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看护理计划对话框 -->
    <el-dialog :title="viewTitle" v-model="viewOpen" width="600px" append-to-body>
      <el-form :model="viewForm" label-width="100px" disabled>
        <el-form-item label="序号">
          <el-input v-model="viewForm.sortNo" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="viewForm.planName" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="formattedCreateTime" />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="viewForm.status === 1 ? 'success' : 'danger'" size="large">
            {{ viewForm.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="viewForm.remark" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/nursing/plan";
import { ref, reactive, toRefs, computed, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();

const planList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const viewTitle = ref("");
const viewForm = ref({});
const { nursing_project_status } = proxy.useDict("nursing_project_status");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sortNo: null,
    planName: null,
    status: null,
  },
  rules: {
    sortNo: [
      { required: true, message: "序号不能为空", trigger: "blur" }
    ],
    planName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态 不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询护理计划列表 */
function getList() {
  loading.value = true;
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sortNo: null,
    planName: null,
    status: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("planRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPlan(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改护理计划";
  });
}

/** 查看按钮操作 */
function handleGet(row) {
  const _id = row.id || ids.value;
  getPlan(_id).then(response => {
    viewForm.value = response.data;
    viewTitle.value = `查看护理计划 - ${response.data.planName}`;
    viewOpen.value = true;
  }).catch(error => {
    proxy.$modal.msgError("获取数据失败");
    console.error(error);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除护理计划编号为"' + _ids + '"的数据项？').then(function() {
    return delPlan(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nursing/plan/export', {
    ...queryParams.value
  }, `plan_${new Date().getTime()}.xlsx`);
}

getList();

/** 启用或禁用操作 **/
function handleEnable(row) {
  const status = row.status === 1 ? 0 : 1;
  const msg = row.status === 1 ? '禁用' : '启用';
  const data = {
    id: row.id,
    status: status
  };
  proxy.$modal.confirm(`是否确认${msg}${row.planName}护理计划`)
      .then(function () {
        updatePlan(data).then((response) => {
          proxy.$modal.msgSuccess(`${msg}成功`);
          getList();
        }).catch(() => {
          proxy.$modal.msgError(`${msg}失败`);
        });
      });
}

// 计算属性，格式化创建时间
const formattedCreateTime = computed(() => {
  return parseTime(viewForm.value.createTime, '{y}-{m}-{d} {h}:{i}:{s}');
});

// 确保 parseTime 方法存在
function parseTime(time, pattern) {
  // 假设 parseTime 方法已经定义
  // 如果没有定义，可以使用 moment.js 或其他日期库
  // 这里假设 parseTime 是一个全局方法
  return proxy.parseTime(time, pattern);
}
</script>
